package com.taomus.mytools.lang.java;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taomus.mytools.lang.IInvoke;
import com.taomus.mytools.lang.IMethod;

public class JavaMethod implements IMethod {
	private static final Logger logger = LoggerFactory
			.getLogger(JavaMethod.class);
	private Class<?> cl = null;
	private Object obj = null;

	public JavaMethod(Class<?> cl,Object obj) {
		this.cl = cl;
		this.obj = obj;
	}

	public static class JavaInvoke implements IInvoke {

		private String name = null;
		private Class<?> cl = null;
		private Object obj = null;

		public JavaInvoke(String name, Class<?> cl,Object obj) {
				this.name = name;
				this.cl = cl;
				this.obj = obj;
		}

		@Override
		public Object invoke() {
			return this.invoke(new Object[] { null });
		}

		@Override
		public Object invoke(Object... args) {
			try {
				if (args.length > 0) {
					if (args[0] == null) {
						return this.cl.getMethod(this.name).invoke(this.obj);
					}
					int len = args.length;
					Class<?>[] cs = new Class[len];
					for (int i = 0; i < len; i++) {
						cs[i] = args[i].getClass();
					}
					return this.cl.getMethod(this.name, cs).invoke(this.obj, args);
				}
			} catch (Exception e) {
				logger.error("javaMethod", e);
			}
			return null;
		}

	}

	@Override
	public IInvoke getMethod(String name) {
		return new JavaInvoke(name, cl,obj);
	}
}
